<script lang="ts">
    import type { NodeKeyType } from "../Tree";
    import type { CascaderNode, OptionProps } from "./Cascader";
    import { useCascaderContext } from "./Cascader.svelte";

    const props: OptionProps = $props();
    const { store } = props;
    const ctx: any = useCascaderContext();
    const title = $derived(props.data.map((item: CascaderNode) => item[store.titleField]).join(" / "));
    const onClick = () => {
        const lastItem = props.data[props.data.length - 1];
        if (lastItem.disabled) {
            return;
        }
        const vals: NodeKeyType[] = props.data.map((item) => item[store.valueField]);
        if (ctx?.multi) {
            if (props.filter) {
                ctx?.clearQuery("");
            }
            store.checkNode(vals[vals.length - 1], true);
        } else {
            store.setSelectedKey(vals);
            ctx?.onSelect(props.data[props.data.length - 1]);
        }
    };

    const classList = $derived({
        "cm-cascader-item": true,
        "cm-cascader-item-checked": props.data[props.data.length - 1].checked,
        "cm-cascader-item-disabled": props.data[props.data.length - 1].disabled,
    });
</script>

<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div class={classList} onclick={onClick}>
    {title}
</div>
